package com.hdu.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdu.entity.Link;
import com.hdu.enums.LinkLabel;
import com.hdu.mapper.LinkMapper;
import com.hdu.pojo.PageBean;
import com.hdu.pojo.Sort;
import com.hdu.service.ILinkService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 链接实体类 服务实现类
 * </p>
 *
 * @author xiaobai
 * @since 2025-02-07
 */
@Service
@RequiredArgsConstructor
public class LinkServiceImpl extends ServiceImpl<LinkMapper, Link> implements ILinkService {

    private final LinkMapper linkMapper;

    /**
     * 网站链接查询
     */
    @Override
    public PageBean<Link> page(Integer current, Integer size, String name) {
        //1. 设置分页参数
        Page<Link> page = new Page<>(current, size);

        QueryWrapper<Link> wrapper = new QueryWrapper<>();
        wrapper.eq(!StrUtil.isEmpty(name), "name", name);

        IPage<Link> iPage = linkMapper.selectPage(page, wrapper);

        return new PageBean<>(iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 网站链接分类查询
     */
    @Override
    public List<Sort> sortLink() {
        List<Sort> sortList = new ArrayList<>();
        Map<LinkLabel, List<Link>> map = list().stream().collect(Collectors.groupingBy(Link::getLabel));
        for (LinkLabel label : map.keySet()) {
            Sort sort = new Sort(label.getDesc(), "", map.get(label));
            sortList.add(sort);
        }
        return sortList;
    }

    /**
     * 新增网站链接
     */
    @Override
    public void append(Link link) {
        int num = link.getLabel().getValue() * 100 + 1;
        for (int i = num; i < num + 99; i++) {
            if (linkMapper.selectById(i) == null) {
                link.setId(i);
                break;
            }
        }
        linkMapper.insert(link);
    }
}

